﻿using Kanban.Common;
using Kanban.DALContainer;
using Kanban.IBLL;
using Kanban.IDal;
using Kanban.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Kanban.BLL
{
    public class UserService : BaseService<UserId_仓码对应表>, IUserService
    {
        private readonly IUserDAL UserDAL = Container.Resolve<IUserDAL>();

        public override void SetCurrentDal()
        {
            Dal = UserDAL;
        }

        public Task<UserId_仓码对应表> GetModelAsync(string name, string pwd)
        {
            string hashPassword = StringHelper.Md5(pwd);
            return UserDAL.GetModelAsync(name, hashPassword);
        }

        public async Task<Tuple<IList<object>, int>> GetModelsByPageAsync(string search, int pageSize, int pageIndex)
        {
            return await UserDAL.GetModelsByPageAsync(search, pageSize, pageIndex);
        }


        public async Task<bool> Save(UserId_仓码对应表 model)
        {
            var query = await GetModelAsync(model.Id);
            if (query == null)
            {
                model.IsValid = true;
                model.CreateTime = DateTime.Now;
                model.Password = StringHelper.Md5("123456");
                return await AddAsync(model) > 0;
            }
            else
            {
                query.UserNo = model.UserNo;
                query.UserName = model.UserName;
                query.Code_仓码 = model.Code_仓码;
                query.Type = model.Type;
                query.IsValid = model.IsValid;
                query.Memo = model.Memo;
                query.Roles = model.Roles;
                return await UpdateAsync(query) > 0;
            }
        }

        public async Task<bool> EditPassword(int id, string password, string newPassword)
        {
            var query = await GetModelAsync(id);
            if(query.Password != StringHelper.Md5(password))
            {
                return false;
            }
            query.Password = StringHelper.Md5(newPassword);
            return await UpdateAsync(query) > 0;
        }
    }
}
